<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Role;
use think\Db;
use app\admin\model\User as UserModel;
use app\common\model\Department;
use app\common\service\UserPermissionService;


/**
 * 系统接口
 */
class Task extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

  

    /**
     * 更新客户状态 - 异步处理版本
     * 立即返回响应，后台异步处理
     */
    public function execute()
    {
       
        // 检查是否已有任务在运行
        $runningTask = Db::name('task_log')
            ->where('task_name', 'update_customer_status')
            ->where('status', 'running')
            ->where('start_time', '>', date('Y-m-d H:i:s', strtotime('-1 hour'))) // 1小时内的任务
            ->find();
            
        if ($runningTask) {
            $this->success('任务已在运行中', [
                'task_id' => $runningTask['id'],
                'start_time' => $runningTask['start_time']
            ]);
            return;
        }
        
        // 创建任务记录
        $taskId = Db::name('task_log')->insertGetId([
            'task_name' => 'update_customer_status',
            'status' => 'running',
            'start_time' => date('Y-m-d H:i:s'),
            'total_count' => 0,
            'processed_count' => 0,
            'updated_count' => 0,
            'error_message' => '',
            'createtime' => time()
        ]);
        
        // 在返回响应前注册关机回调，确保后台处理会在响应结束后执行
        register_shutdown_function(function() use ($taskId) {
            // 使用当前实例方法执行后台任务
            $this->processTaskInBackground($taskId);
        });
        
        // 立即返回响应
        $this->success('任务已启动', [
            'task_id' => $taskId,
            'message' => '任务正在后台处理中，请稍后查询状态'
        ]);
        
        // 注意：此处不再直接调用 $this->processTaskInBackground($taskId);
        // 因为 success 会抛出响应异常并中断后续代码，使用 register_shutdown_function 来执行后台逻辑
            
      
    }
    
    /**
     * 后台处理任务
     */
    private function processTaskInBackground($taskId)
    {
        // 设置后台执行
        if (function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        }
        
        ignore_user_abort(true);
        set_time_limit(0);
        ini_set('memory_limit', '2G');
        
        try {
            $updateCount = 0;
            $processedCount = 0;
            $batchSize = 1000; // 减小批次大小，避免内存问题
            $offset = 0;
            
            // 获取总数量
            $totalCount = Db::name('customer')->where('is_delete', 0)->count();
            
            // 更新任务总数量
            Db::name('task_log')->where('id', $taskId)->update(['total_count' => $totalCount]);
            
            do {
                // 分批获取客户数据
                $customers = Db::name('customer')
                    ->where('is_delete', 0)
                    ->field('id,productName,filingTime,mailDate,filingCaseNo,court,courtPhone,executionCaseNo,status')
                    ->limit($offset, $batchSize)
                    ->select();
                
                if (empty($customers)) {
                    break;
                }
                
                // 批量获取相关数据
                $customerIds = array_column($customers, 'id');
                $contractsData = $this->getContractsData($customerIds);
                $paymentPlanData = $this->getPaymentPlanData($customerIds);
                
                // 批量更新状态
                $updateData = [];
                foreach ($customers as $customer) {
                    $newStatus = $this->calculateCustomerStatus($customer, $contractsData, $paymentPlanData);
                    
                    if ($customer['status'] != $newStatus) {
                        $updateData[] = [
                            'id' => $customer['id'],
                            'status' => $newStatus
                        ];
                    }
                }
                
                // 批量更新数据库
                if (!empty($updateData)) {
                    $this->batchUpdateStatus($updateData);
                    $updateCount += count($updateData);
                }
                
                $processedCount += count($customers);
                $offset += $batchSize;
                
                // 更新任务进度
                Db::name('task_log')->where('id', $taskId)->update([
                    'processed_count' => $processedCount,
                    'updated_count' => $updateCount,
                    'progress' => round(($processedCount / $totalCount) * 100, 2)
                ]);
                
                // 释放内存
                unset($customers, $contractsData, $paymentPlanData, $updateData);
                
                // 每处理一批后休息一下
                usleep(50000); // 休息0.05秒
                
            } while (true);
            
            // 任务完成
            Db::name('task_log')->where('id', $taskId)->update([
                'status' => 'completed',
                'end_time' => date('Y-m-d H:i:s'),
                'progress' => 100
            ]);
            
        } catch (\Exception $e) {
            // 任务失败
            Db::name('task_log')->where('id', $taskId)->update([
                'status' => 'failed',
                'end_time' => date('Y-m-d H:i:s'),
                'error_message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * 查询任务状态
     */
    public function getTaskStatus()
    {
        $taskId = $this->request->get('task_id');
        
        if (!$taskId) {
            $this->error('缺少任务ID');
        }
        
        $task = Db::name('task_log')->where('id', $taskId)->find();
        
        if (!$task) {
            $this->error('任务不存在');
        }
        
        $this->success('查询成功', $task);
    }
    
    /**
     * 获取最新任务状态
     */
    public function getLatestTaskStatus()
    {
        $task = Db::name('task_log')
            ->where('task_name', 'update_customer_status')
            ->order('id desc')
            ->find();
            
        if (!$task) {
            $this->error('暂无任务记录');
        }
        
        $this->success('查询成功', $task);
    }

    /**
     * 批量获取客户还款协议数据
     */
    private function getContractsData($customerIds)
    {
        $contracts = Db::name('contracts')
            ->where('customer_id', 'in', $customerIds)
            ->where('is_delete', 0)
            ->field('customer_id')
            ->select();
            
        $result = [];
        foreach ($contracts as $contract) {
            $result[$contract['customer_id']] = true;
        }
        
        return $result;
    }

    /**
     * 批量获取客户还款计划数据
     */
    private function getPaymentPlanData($customerIds)
    {
        $paymentPlans = Db::name('payment_plan')
            ->where('customer_id', 'in', $customerIds)
            ->where('status', '待回款')
            ->where('is_delete', 0)
            ->field('customer_id')
            ->select();
            
        $result = [];
        foreach ($paymentPlans as $plan) {
            $result[$plan['customer_id']] = true;
        }
        
        return $result;
    }

    /**
     * 批量更新客户状态
     */
    private function batchUpdateStatus($updateData)
    {
        if (empty($updateData)) {
            return;
        }

        $ids = [];
        $cases = [];
        foreach ($updateData as $item) {
            $ids[] = (int)$item['id'];
            $cases[] = "WHEN {$item['id']} THEN {$item['status']}";
        }
        $idsStr = implode(',', $ids);
        $casesStr = implode(' ', $cases);

        $sql = "UPDATE fa_customer SET status = CASE id {$casesStr} END WHERE id IN ({$idsStr})";
        Db::execute($sql);
    }

    /**
     * 计算客户状态
     * @param array $customer 客户信息
     * @param array $contractsData 还款协议数据
     * @param array $paymentPlanData 还款计划数据
     * @return int 状态值
     */
    private function calculateCustomerStatus($customer, $contractsData = [], $paymentPlanData = [])
    {
        $customerId = $customer['id'];
        $productName = $customer['productName'];
        
        // 优先级从高到低：6 → 5 → 4 → 3 → 2 → 1
        
        // 6. 退案②：产品名称包含“退案”，且有还款协议
        if (strpos($productName, '退案') !== false) {
            $hasContractInDismiss = isset($contractsData[$customerId]);
            if ($hasContractInDismiss) {
                return 6;
            }
        }
        
        // 5. 退案①：产品名称包含“退案”，且无还款协议
        if (strpos($productName, '退案') !== false) {
            $hasContractInDismiss = isset($contractsData[$customerId]);
            if (!$hasContractInDismiss) {
                return 5;
            }
        }
        
        // 合同/计划标记（供后续复用）
        $hasContract = isset($contractsData[$customerId]);
        $hasPendingPayment = isset($paymentPlanData[$customerId]);
        
        // 4. 已完结：有还款协议，且没有“待回款”的还款计划
        if ($hasContract && !$hasPendingPayment) {
            return 4;
        }
        
        // 3. 还款中：有还款协议，且存在“待回款”的还款计划
        if ($hasContract && $hasPendingPayment) {
            return 3;
        }
        
        // 2. 已立案：6个立案字段至少填写一个
        $filingFields = [
            'filingTime',
            'mailDate',
            'filingCaseNo',
            'court',
            'courtPhone',
            'executionCaseNo'
        ];
        $filledCount = 0;
        foreach ($filingFields as $field) {
            if (!empty($customer[$field])) {
                $filledCount++;
            }
        }
        if ($filledCount > 0) {
            return 2;
        }
        
        // 1. 进行中：上述都不满足（6个字段均未填，且无合同等）
        return 1;
    }


   


}

